import React, { useState, useEffect } from 'react';
import { get, post, put, del } from '../utils/api';
import { useAuth } from '../contexts/AuthContext';
import { encryptPassword } from '../utils/password';
import './Users.css';

interface User {
  id: string;
  username: string;
  role: 'admin' | 'user';
  createdAt: string;
  updatedAt: string;
}

interface UserFormData {
  username: string;
  password: string;
  role: 'admin' | 'user';
}

const Users: React.FC = () => {
  const { user: currentUser } = useAuth();
  const [users, setUsers] = useState<User[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [showModal, setShowModal] = useState(false);
  const [editingUser, setEditingUser] = useState<User | null>(null);
  const [searchTerm, setSearchTerm] = useState('');
  const [filterRole, setFilterRole] = useState<string>('all');

  const [formData, setFormData] = useState<UserFormData>({
    username: '',
    password: '',
    role: 'user'
  });

  useEffect(() => {
    fetchUsers();
  }, []);

  const fetchUsers = async () => {
    try {
      setLoading(true);
      const response = await get('/users');
      if (response.success) {
        setUsers(response.data);
      } else {
        setError('获取用户列表失败');
      }
    } catch (error) {
      console.error('Failed to fetch users:', error);
      setError('获取用户列表失败');
    } finally {
      setLoading(false);
    }
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    if (!formData.username.trim()) {
      setError('请输入用户名');
      return;
    }

    if (!editingUser && !formData.password.trim()) {
      setError('请输入密码');
      return;
    }

    try {
      if (editingUser) {
        const updateData: any = {
          username: formData.username,
          role: formData.role
        };
        
        // 只有在输入了新密码时才更新密码
        if (formData.password.trim()) {
          updateData.password = encryptPassword(formData.password);
        }

        const response = await put(`/users/${editingUser.id}`, updateData);
        if (response.success) {
          await fetchUsers();
          resetForm();
          setShowModal(false);
        } else {
          setError(response.message || '更新用户失败');
        }
      } else {
        const response = await post('/users', {
          ...formData,
          password: encryptPassword(formData.password)
        });
        if (response.success) {
          await fetchUsers();
          resetForm();
          setShowModal(false);
        } else {
          setError(response.message || '添加用户失败');
        }
      }
    } catch (error) {
      setError('操作失败，请稍后重试');
    }
  };

  const handleEdit = (user: User) => {
    setEditingUser(user);
    setFormData({
      username: user.username,
      password: '',
      role: user.role
    });
    setShowModal(true);
  };

  const handleDelete = async (id: string) => {
    if (id === currentUser?.id) {
      setError('不能删除当前登录的用户');
      return;
    }

    if (!window.confirm('确定要删除这个用户吗？')) {
      return;
    }

    try {
      const response = await del(`/users/${id}`);
      if (response.success) {
        await fetchUsers();
      } else {
        setError(response.message || '删除用户失败');
      }
    } catch (error) {
      setError('删除失败，请稍后重试');
    }
  };

  const resetForm = () => {
    setFormData({
      username: '',
      password: '',
      role: 'user'
    });
    setEditingUser(null);
    setError('');
  };

  const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>) => {
    const { name, value } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: value
    }));
  };

  // 过滤用户
  const filteredUsers = users.filter(user => {
    const matchesSearch = user.username.toLowerCase().includes(searchTerm.toLowerCase());
    const matchesRole = filterRole === 'all' || user.role === filterRole;
    
    return matchesSearch && matchesRole;
  });

  const formatDate = (dateString: string) => {
    return new Date(dateString).toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    });
  };

  const getRoleText = (role: string) => {
    switch (role) {
      case 'admin':
        return '管理员';
      case 'user':
        return '普通用户';
      default:
        return role;
    }
  };

  const getRoleColor = (role: string) => {
    switch (role) {
      case 'admin':
        return 'primary';
      case 'user':
        return 'secondary';
      default:
        return 'secondary';
    }
  };

  if (loading) {
    return (
      <div className="users-loading">
        <div className="spinner"></div>
        <p>加载用户数据...</p>
      </div>
    );
  }

  return (
    <div className="users">
      <div className="users-header">
        <h1>用户管理</h1>
        <button 
          onClick={() => setShowModal(true)} 
          className="btn btn-primary"
        >
          <span className="btn-icon">➕</span>
          添加用户
        </button>
      </div>

      {error && (
        <div className="alert alert-error">
          {error}
          <button onClick={() => setError('')} className="alert-close">×</button>
        </div>
      )}

      {/* 搜索和过滤 */}
      <div className="users-controls">
        <div className="search-box">
          <input
            type="text"
            placeholder="搜索用户名..."
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
            className="search-input"
          />
        </div>
        
        <div className="filter-box">
          <select
            value={filterRole}
            onChange={(e) => setFilterRole(e.target.value)}
            className="filter-select"
          >
            <option value="all">所有角色</option>
            <option value="admin">管理员</option>
            <option value="user">普通用户</option>
          </select>
        </div>
      </div>

      {/* 统计信息 */}
      <div className="users-stats">
        <div className="stat-item">
          <div className="stat-label">总用户数</div>
          <div className="stat-value">{users.length}</div>
        </div>
        <div className="stat-item primary">
          <div className="stat-label">管理员</div>
          <div className="stat-value">{users.filter(user => user.role === 'admin').length}</div>
        </div>
        <div className="stat-item secondary">
          <div className="stat-label">普通用户</div>
          <div className="stat-value">{users.filter(user => user.role === 'user').length}</div>
        </div>
      </div>

      {/* 用户列表 */}
      <div className="users-list">
        {filteredUsers.length > 0 ? (
          <div className="users-table">
            <table>
              <thead>
                <tr>
                  <th>用户名</th>
                  <th>角色</th>
                  <th>创建时间</th>
                  <th>最后更新</th>
                  <th>操作</th>
                </tr>
              </thead>
              <tbody>
                {filteredUsers.map((user) => (
                  <tr key={user.id} className={user.id === currentUser?.id ? 'current-user' : ''}>
                    <td className="username">
                      {user.username}
                      {user.id === currentUser?.id && (
                        <span className="current-indicator">（当前用户）</span>
                      )}
                    </td>
                    <td>
                      <span className={`role-badge ${getRoleColor(user.role)}`}>
                        {getRoleText(user.role)}
                      </span>
                    </td>
                    <td className="date">{formatDate(user.createdAt)}</td>
                    <td className="date">{formatDate(user.updatedAt)}</td>
                    <td className="actions">
                      <button
                        onClick={() => handleEdit(user)}
                        className="btn btn-sm btn-secondary"
                        title="编辑"
                      >
                        ✏️
                      </button>
                      {user.id !== currentUser?.id && (
                        <button
                          onClick={() => handleDelete(user.id)}
                          className="btn btn-sm btn-danger"
                          title="删除"
                        >
                          🗑️
                        </button>
                      )}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        ) : (
          <div className="empty-state">
            <div className="empty-icon">👥</div>
            <h3>
              {searchTerm || filterRole !== 'all' ? '没有找到匹配的用户' : '暂无用户'}
            </h3>
            <p>
              {searchTerm || filterRole !== 'all' 
                ? '请尝试调整搜索条件或过滤器' 
                : '开始添加您的第一个用户'
              }
            </p>
            {(!searchTerm && filterRole === 'all') && (
              <button 
                onClick={() => setShowModal(true)} 
                className="btn btn-primary"
              >
                添加用户
              </button>
            )}
          </div>
        )}
      </div>

      {/* 添加/编辑模态框 */}
      {showModal && (
        <div className="modal-overlay" onClick={() => {
          setShowModal(false);
          resetForm();
        }}>
          <div className="modal" onClick={(e) => e.stopPropagation()}>
            <div className="modal-header">
              <h2>{editingUser ? '编辑用户' : '添加用户'}</h2>
              <button 
                onClick={() => {
                  setShowModal(false);
                  resetForm();
                }}
                className="modal-close"
              >
                ×
              </button>
            </div>

            <form onSubmit={handleSubmit} className="modal-form">
              <div className="form-group">
                <label className="form-label">
                  用户名 <span className="required">*</span>
                </label>
                <input
                  type="text"
                  name="username"
                  value={formData.username}
                  onChange={handleChange}
                  className="form-input"
                  required
                  placeholder="请输入用户名"
                />
              </div>

              <div className="form-group">
                <label className="form-label">
                  密码 {editingUser ? '' : <span className="required">*</span>}
                </label>
                <input
                  type="password"
                  name="password"
                  value={formData.password}
                  onChange={handleChange}
                  className="form-input"
                  required={!editingUser}
                  placeholder={editingUser ? "留空表示不修改密码" : "请输入密码"}
                />
                {editingUser && (
                  <small className="form-hint">
                    留空表示不修改密码
                  </small>
                )}
              </div>

              <div className="form-group">
                <label className="form-label">
                  角色 <span className="required">*</span>
                </label>
                <select
                  name="role"
                  value={formData.role}
                  onChange={handleChange}
                  className="form-select"
                  required
                >
                  <option value="user">普通用户</option>
                  <option value="admin">管理员</option>
                </select>
              </div>

              <div className="modal-actions">
                <button
                  type="button"
                  onClick={() => {
                    setShowModal(false);
                    resetForm();
                  }}
                  className="btn btn-secondary"
                >
                  取消
                </button>
                <button type="submit" className="btn btn-primary">
                  {editingUser ? '更新' : '添加'}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}
    </div>
  );
};

export default Users;
